package com.leyou.item.controller;

import com.Jshop.common.pojo.PageResult;
import com.leyou.item.Service.BrandService;
import com.leyou.item.pojo.Brand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("brand")
public class BrandController {

    //依赖注入Service
    @Autowired
    private BrandService brandService;

    @GetMapping("page")
    public ResponseEntity<PageResult<Brand>> queryBrandByPage(
            @RequestParam(value = "key",required = false) String key,
            @RequestParam(value = "page",defaultValue = "1") Integer page,
            @RequestParam(value = "rows",defaultValue = "5") Integer rows,
            @RequestParam(value = "sortBy",required = false) String sortBy,
            @RequestParam(value = "desc",required = false) Boolean desc
    ){

        PageResult<Brand> result = brandService.queryBrandsByPage(key, page, rows, sortBy, desc);

        if (CollectionUtils.isEmpty(result.getItems())){
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(result);
    }

    //新增品牌
    //注意商品跟分类是多对多关系
    @PostMapping
    public ResponseEntity<Void> saveBrand(Brand brand, @RequestParam(value = "cids") List<Long> cids){

        this.brandService.saveBrand(brand,cids);

        //201
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    //根据分类id查询品牌信息
    @GetMapping("cid/{cid}")
    public ResponseEntity<List<Brand>> queryBrandsByCid(@PathVariable("cid") Long cid){

        List<Brand> brands = this.brandService.queryBrandsByCid(cid);
        if (CollectionUtils.isEmpty(brands)){
            return ResponseEntity.badRequest().build();
        }
        return ResponseEntity.ok(brands);
    }

    //根据id查询品牌
    @GetMapping("/{id}")
    public ResponseEntity<Brand> queryBrandByid(@PathVariable Long id) {
        Brand brand = brandService.queryBrandById(id);
        if (brand == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(brand);
    }

}
